import React, { Component } from 'react';
import ReactDom from 'react-dom';
import { FormattedMessage, injectIntl } from 'react-intl';
import { actions } from "mirrorx";
import { Message, Button, Modal, FormControl,Select } from "tinper-bee";
import Radio from 'bee-radio';
import moment from 'moment'
import DatePicker from "bee-datepicker";
import FormError from 'components/FormError';
import RefComponent from 'components/RefComponent';
import FormList from 'components/FormList'
import './index.less';
let { RangePicker } = DatePicker;

const FormItem = FormList.Item;

class ApprovalModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            personShowName:"",
            approveOpinion:""
        }

    }

    componentWillReceiveProps(nextProps,nextState) {
        let { selectData, ButtonType } = nextProps;
        if (ButtonType == "ButtonApprove" && selectData.length>0 && nextProps.showApprovalModalModal) {
            let param = {
                params: {
                    billId:selectData[0].id
                },
                header: {
                    url: "/occ-cmpt/bpm/processoper/rejectcheck",
                    method: "get",
                },
                callback: (data) => {
                    if(data.body) {
                        this.setState({ rejectList: data.body});
                    }else {
                        this.setState({ rejectList: []});
                    }
                }
            }
            actions.ApprovalModel.getRejectList(param);
        }
    }

    componentDidMount() {
        
    }

    onApprovalModal = () => {
        let { ButtonType, selectData, printTemplateId } = this.props;
        this.props.form.validateFields((err, _values) => {
            let param;
            if (err) {
                Message.create({ content: '请输入值', color: 'warning' });
            } else {

                if (ButtonType == "ButtonApprove") {
                    param = this.setApprovelType(_values);
                    this.setState({
                        personShowName:"",
                        rejectList:null,
                        approveOpinion:""
                    })
                }else {
                    param = {};
                }
                this.props.onCloseApproval({data:param,type: _values.isAgree});
            }
        })
    }

    setApprovelType = (_values) => {
        let {selectData,modalName,bpmService} = this.props;
        let id = selectData[0].id;
        let param;
        let person = _values.person && JSON.parse(_values.person).refpk;
        let refIds = _values.refIds && JSON.parse(_values.refIds).refpk
        switch (_values.isAgree) {
            case "0": {
                param = {
                    data: {
                        billId:id,
                        comment:_values.comment.replace(new RegExp("%(?![0-9a-fA-F]{2})"), "%25"),
                        activityId:_values.activityId || -1
                    },
                    header: {
                        url: "/occ-cmpt/bpm/processoper/reject",
                        method: "post",
                        ContentType: 'application/x-www-form-urlencoded;charset=utf-8',
                    }
                }
                break;
            }
            case "1": {
                param = {
                    params: {
                        comment: _values.comment.replace(new RegExp("%(?![0-9a-fA-F]{2})"), "%25"),
                        type: _values.isAgree
                    },
                    data:selectData,
                    header: {
                        url: bpmService.ButtonApprove.url1,
                        method: "post",
                        // ContentType: 'application/x-www-form-urlencoded;charset=utf-8',
                    }
                }
                break;
            }
            case "2": {
                param = {
                    data:{
                        billId:id,
                        billTypeId:modalName,
                        taskId:"",
                        comment:_values.comment.replace(new RegExp("%(?![0-9a-fA-F]{2})"), "%25"),
                        persons:person
                    },
                    header: {
                        method:"post",
                        url:"/occ-cmpt/bpm/processoper/beforetasksign",
                        // ContentType: 'application/x-www-form-urlencoded;charset=utf-8',
                    },
                }
                break;
            }
            case "3": {
                param = {
                    data:{
                        billId:id,
                        persons:person,
                        billTypeId:modalName,
                        taskId:"",
                        comment:_values.comment.replace(new RegExp("%(?![0-9a-fA-F]{2})"), "%25"),
                        counterSign:true,
                    },
                    header: {
                        method:"post",
                        url:"/occ-cmpt/bpm/processoper/aftersignsumbit",
                        // ContentType: 'application/x-www-form-urlencoded;charset=utf-8',
                    },
                }
                break;
            };
            case "4": {
                param = {
                    data:{
                        billId:id,
                        dPersonId:person,
                        taskId: "",
                        comments:_values.comment.replace(new RegExp("%(?![0-9a-fA-F]{2})"), "%25"),
                    },
                    header: {
                        method:"post",
                        url:"/occ-cmpt/bpm/processoper/delegatetask",
                        ContentType: 'application/x-www-form-urlencoded;charset=utf-8',
                    },
                }
                break;
            };
            case "5": {
                param = {
                    params:{
                        billId:id,
                        refIds:refIds,
                        billTypeId:modalName,
                        // busiTypeId:busiTypeId,
                        comments:_values.comment.replace(new RegExp("%(?![0-9a-fA-F]{2})"), "%25"),
                    },
                    header: {
                        method:"get",
                        url:"/occ-cmpt/bpm/processoper/action-task",
                        // ContentType: 'application/x-www-form-urlencoded;charset=utf-8',
                    },
                }
                break;
            };
            // default: personShowName = null;
        }
        return param;

    }

    openUrl = () => {
        let { htmldata } = this.state;
        window.open(htmldata);
    }

    setPersonShowName = (text) => {
        let personShowName,approveOpinion;
        switch (text) {
            case "0": personShowName = "驳回环节";approveOpinion="不同意"; break;
            case "2": personShowName = "前加签人员"; approveOpinion="请协助审批";break;
            case "3": personShowName = "后加签人员"; approveOpinion="请协助审批";break;
            case "4": personShowName = "改派人员"; approveOpinion="请协助审批";break;
            case "5": personShowName = "处理环节"; approveOpinion="请协助审批";break;
            default: personShowName = null;
        }
        
        this.setState({
            personShowName,approveOpinion
        })
    }

    render() {
        let { form, onCallback, showApprovalModalModal, ButtonType, onCloseApproval, printTemplateId,selectData,modalName } = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        let { personShowName,rejectList,approveOpinion } = this.state;

        let self = this;
        return (
            <Modal
                size={ButtonType == "ButtonApprove" && printTemplateId ? "xlg" : "md"}
                show={showApprovalModalModal}
                autoFocus={false}
                enforceFocus={false}
                onHide={() => onCloseApproval(false)} >
                <Modal.Header>
                    <Modal.Title>审批</Modal.Title>
                </Modal.Header>

                <Modal.Body>
                    {ButtonType != "ButtonApprove" &&
                        <>
                            <h3>确定操作？</h3>
                            <div className="footer-button">
                                <Button onClick={() => {onCloseApproval(false)}} style={{ marginRight: 10 }}><FormattedMessage id="js.Ref.Ref224.0012" defaultMessage="关闭" /></Button>
                                <Button onClick={this.onApprovalModal} ><FormattedMessage id="js.com.Pas.0005" defaultMessage="确定" /></Button>
                            </div>
                        </>
                    }
                    {ButtonType == "ButtonApprove" && <>
                        <FormItem
                            label={'批准'}
                            FormError={<FormError errorMsg={getFieldError(`comment`)} />}
                        >
                            <Radio.RadioGroup
                                {
                                ...getFieldProps(`isAgree`, {
                                    initialValue: "1",
                                    onChange: (text) => {
                                        self.setPersonShowName(text);
                                    },
                                    rules: [{
                                        required: true,
                                        message: '请选择',
                                    }],
                                }
                                )}
                            >
                                <Radio value="1">同意</Radio>
                                <Radio value="0">驳回</Radio>
                                <Radio value="2">前加签</Radio>
                                <Radio value="3">后加签</Radio>
                                <Radio value="4">改派</Radio>
                                <Radio value="5">指派下一环节</Radio>
                            </Radio.RadioGroup>
                        </FormItem>
                        {personShowName && personShowName != "处理环节" && personShowName != "驳回环节" && <FormItem
                            label={personShowName}
                            FormError={<FormError errorMsg={getFieldError(`person`)} />}
                        >
                            <RefComponent
                                multiple={true}
                                key={`person`}
                                title={"人员"}
                                refName={"approvePersonRef"} //terminalPersonRef
                                childType={"DataHeader"}
                                clearMatchData={this.clearMatch}

                                fieldName={"person"}
                                refTableOnClickSave={(refName, fieldName, data) => {
                                    // self.savePerson(data);
                                }}
                                form={this.props.form}
                            />
                        </FormItem>}
                        {personShowName == "处理环节" && <FormItem
                            label={this.state.personShowName}
                            required={true}
                            FormError={<FormError errorMsg={getFieldError(`refIds`)} />}
                        >
                            <RefComponent
                                multiple={true}
                                key={`refIds`}
                                title={"处理环节"}
                                refName={"assignCheck"}
                                clearMatchData={this.clearMatch}
                                constparam={{EQ_billId:selectData[0].id,EQ_billTypeId:modalName}}
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择处理环节',
                                        pattern: /[^{"refname":"","refpk":"","refcode":""}|{"refpk":"","refname":"","refcode":""}]/
                                    }
                                ]}
                                fieldName={"refIds"} 
                                refTableOnClickSave={(refName, fieldName, data) => {
                                    // self.savePerson(data);
                                }}
                                form={this.props.form}
                            />
                        </FormItem>}
                        {personShowName == "驳回环节" && <FormItem
                            label={"驳回环节"}
                            FormError={<FormError errorMsg={getFieldError(`activityId`)} />}
                        >
                            <Select
                                key={`activityId`}
                                {
                                ...getFieldProps("activityId", {
                                    rules: [{
                                        message: '请选择',
                                    }],
                                })
                                }
                            >
                                {
                                    rejectList && rejectList.map((item, index) => {
                                        return (
                                            <Option key={`${item.activityId}`} value={item.activityId}>{item.activityName}</Option>
                                        )
                                    })
                                }

                            </Select>
                        </FormItem>}
                        <FormItem
                            label={'批语'}
                        >
                            <FormControl
                                componentClass={"textarea"}
                                {...getFieldProps('comment', {
                                    initialValue: approveOpinion||"同意",
                                    rules: [{
                                        message: "请输入",
                                    }],
                                })}
                            />
                        </FormItem>
                        <div className="footer-button">
                            <Button onClick={
                                    () => {
                                        this.setState({
                                            personShowName:"",
                                            rejectList:null,
                                            approveOpinion:""
                                        },
                                        ()=>{
                                            onCloseApproval(false)
                                        })
                                    }
                                }  style={{ marginRight: 10 }}><FormattedMessage id="js.Ref.Ref224.0012" defaultMessage="关闭" /></Button>
                            <Button onClick={this.onApprovalModal} ><FormattedMessage id="js.com.Pas.0005" defaultMessage="确定" /></Button>
                            {/* <Button onClick={this.openUrl} >浏览附件</Button> */}
                        </div>

                    </>
                    }
                </Modal.Body>
            </Modal>

        )
    }
}

export default FormList.createForm()(injectIntl(ApprovalModal))
